<template>
    <view class="select-container" @click.stop>
        <view class="select-display row items-center" @click="toggleDropdown" :style="customStyle">
            <image src="/static/images/data/down.png" style="width: 16rpx; height: 8rpx" />
            <view class="mx-xs">{{ nameKey && selectedOption ? selectedOption[nameKey] : selectedOption || $t('please_select') }}</view>
        </view>
        <view v-if="dropdownOpen" class="select-dropdown">
            <view v-for="(option, index) in options" :key="index" class="select-option" @click="selectOption(option)">
                {{ nameKey && selectedOption ? option[nameKey] : option }}
            </view>
        </view>
    </view>
</template>
  
  <script>
export default {
    props: {
        options: {
            type: Array,
            default: () => [],
        },
        nameKey: {
            type: String,
            default: '',
        },
        customStyle: {
            type: String,
            default: 'backgroundColor: #f8f8f8;border: 1px solid #ddd;',
        },
        selectedOption: {
            type: String | Object,
            default: null,
        },
    },
    data() {
        return {
            dropdownOpen: false,
        }
    },
    methods: {
        toggleDropdown() {
            this.dropdownOpen = !this.dropdownOpen
        },
        selectOption(option) {
            this.$emit('change', option)
            this.dropdownOpen = false
        },
        handleClickOutside(event) {
            if (!this.$el.contains(event.target)) {
                this.dropdownOpen = false
            }
        },
    },
    mounted() {
        // #ifdef H5
        document.addEventListener('click', this.handleClickOutside)
        // #endif
        uni.$on('pageClick', () => {
            this.dropdownOpen = false
        })
    },
    beforeDestroy() {
        // #ifdef H5
        document.removeEventListener('click', this.handleClickOutside)
        // #endif
    },
}
</script>
  
  <style scoped>
.select-container {
    position: relative;
    display: inline-block;
    min-width: 150rpx;
}

.select-display {
    padding: 10px;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
}

.select-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.select-option {
    padding: 10px;
    cursor: pointer;
    text-align: center;
}

.select-option:hover {
    background-color: #f0f0f0;
}
</style>
  